const express = require('express');
const router = express.Router();
const { registerMember, loginMember } = require('../models/Member');
const jwt = require('jsonwebtoken');

// 注册接口
router.post('/register', (req, res) => {
  const { name, email, password, phone } = req.body;
  registerMember(name, email, password, phone, (err, result) => {
    if (err) return res.status(500).send('注册失败');
    res.status(201).send('注册成功');
  });
});

// 登录接口（生成JWT令牌）
router.post('/login', (req, res) => {
  const { email, password } = req.body;
  loginMember(email, (err, results) => {
    if (err || !results.length) return res.status(401).send('用户不存在');
    bcrypt.compare(password, results[0].password, (err, isMatch) => {
      if (isMatch) {
        const token = jwt.sign(
          { userId: results[0].id },
          process.env.JWT_SECRET,
          { expiresIn: '1h' }
        );
        res.json({ token, member: results[0] });
      } else {
        res.status(401).send('密码错误');
      }
    });
  });
});

module.exports = router;